package com.alfayun.fiscalriskanalysis.reportspec;

import java.util.List;
import java.util.Optional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Order;
import org.springframework.stereotype.Service;

@Service
public class ColumnSpecService {

	@Autowired
	private ColumnSpecRepository repository;
	
	public List<ColumnSpec> list() {
		return repository.findAll(Sort.by(Order.desc("id")));
	}
	
	public ColumnSpec queryById(int id) throws NoSuchColumnSpecException {
		return repository.findById(id).orElseThrow(NoSuchColumnSpecException::new);
	}
	
	public ColumnSpec newColumnSpec(ColumnSpec columnSpec) {
		return ColumnSpec.newColumnSpec(repository, columnSpec);
	}

	public void deleteColumnSpec(int id) {
		repository.deleteById(id);
	}

	public ColumnSpec modifyColumnSpec(int id, ColumnSpec columnSpec) throws NoSuchColumnSpecException {
		Optional<ColumnSpec> column = repository.findById(id);

		if (column.isPresent()) {
			return repository.save(columnSpec);
		}

		throw new NoSuchColumnSpecException();
	}
	
}
